package com.lcd.ssm.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lcd.ssm.domain.Employee;
import com.lcd.ssm.domain.Log;
import com.lcd.ssm.service.ILogService;
import org.aspectj.lang.JoinPoint;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * lcd  2020/4/29
 * Description:
 */
public class LogAspect {
    @Autowired
    private ILogService logService;
    public void write(JoinPoint joinPoint){
        //自己切自己
        if(joinPoint.getTarget() instanceof ILogService){
            return;
        }
        Log log = new Log();
        log.setOptime(new Date());
        String function=(joinPoint.getTarget().getClass().getName()+":"+joinPoint.getSignature().getName());
        log.setFunction(function);
        HttpServletRequest request = UserContext.getRequest();
        Employee employee = (Employee) request.getSession().getAttribute(UserContext.USER_SESSION);
        log.setOpuser(employee);
        log.setOpip(request.getRemoteAddr());
        try {
            Object[] args = joinPoint.getArgs();
            ObjectMapper objectMapper = new ObjectMapper();
            log.setParams(objectMapper.writeValueAsString(args));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        logService.insert(log);
    }
}
